package cn.zhxu.toys.cipher;

import cn.zhxu.toys.util.DigestUtils;
import org.apache.commons.codec.binary.Base64;

import java.nio.charset.StandardCharsets;


/**
 * 
 * @author Administrator
 *
 */
public class ZLEncryptor implements Encryptor {


	private String secret;
	
	
	@Override
	public void init(String secret) {
		this.secret = secret;
	}

	
	@Override
	public byte[] encrypt(byte[] plainBytes) {
		return encrypt(secret.getBytes(StandardCharsets.UTF_8), plainBytes);
	}


	@Override
	public byte[] encrypt(byte[] secretBytes, byte[] plainBytes) {	
		try {
			secretBytes = DigestUtils.toMd5(secretBytes);
			int mod = 0;
			for (byte b : plainBytes) {
				mod = (mod + b) % 255;
			}
			int textLength = plainBytes.length;
			byte[] encryptBytes = new byte[2 * textLength + 1];
			encryptBytes[0] = (byte) mod;
			for (int i = 0; i < textLength; i++) {
				byte textByte = plainBytes[i];
				byte secertByte = secretBytes[i % secretBytes.length];
				int sum = (int) textByte + (int) secertByte;
				int right = sum / 2;
				int left = mod + sum % 2;
				encryptBytes[2 * i + 1] = (byte) left;
				encryptBytes[2 * i + 2] = (byte) right;
			}
			return encryptBytes;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	
	@Override
	public String encrypt(String plainText) {
		return encrypt(secret, plainText);
	}

	
	@Override
	public String encrypt(String secretText, String plainText) {	
		byte[] secretBytes = secretText.getBytes(StandardCharsets.UTF_8);
		byte[] plainBytes = plainText.getBytes(StandardCharsets.UTF_8);
		byte[] bytes = encrypt(secretBytes, plainBytes);
		return Base64.encodeBase64String(bytes);
	}
	
}
